<?php
namespace Home\Model;

use Think\Model;

class UserModel extends Model
{
    private $user = array();
    protected $_validate = array(
        array("mobile", "/^1[3456789][0-9]{9}$/", "手机号格式不正确"), array("password", "require", "密码必须填写"), array("user_type", "0,1", "用户类型不对", 0, "in"),
    );

    /**
     * 获取一个用户的详细信息
     * @param int $uid 用户的id
     * @return array 用户信息数组
     */
    public function getUser($uid) {
        $this->user = $this->where(array('id' => $uid))->find();
        if (empty($this->user)) return null;
        unset($this->user['password']);
        return $this->user;

    }

    public function baseInfo($uid = null) {
        $base_info = M('UserInfo')->where(array('uid' => $uid))->find();
        $user = M('User')->where(array('id' => $uid))->field("mobile")->find();

        $base_info = array_merge($base_info, $user);
        return $base_info;
    }

    /***is a volidate password**/
    public function isTruePassword($pwd, $uid) {
        $password = $this->where(array('id' => $uid))->getField("password");
        if (crpypassword($pwd) != $password) return false;
        return true;
    }

    /**update password ***/
    public function updatePassword($uid, $password) {
        return $this->where(array('id' => $uid))->save(array('password' => crpypassword($password)));

    }

    public function hasMobile($mobile) {
        $count = $this->where(array('mobile' => $mobile))->count();
        return ($count) ? true : false;
    }

    public function checkLogin($password, $email) {
        $user = $this->where(array('email' => $email))->find();
        if (empty($user)) {
            $user = $this->where(array("mobile" => $email))->find();
        }
        if (empty($user)) return -1;
        if ($user['password'] != crpypassword($password)) return -2;

        return $user['id'];
    }

    // V0.9 注册成为用户
    public function addUser() {
        $this->password = crpypassword(trim($this->password));
        $this->nick_name = null;
        $this->last_login_time = $this->reg_time = time();
        return $this->add();
    }
}